package com.aaa.book_mall.controller;

import com.aaa.book_mall.dao.UserDao;
import com.aaa.book_mall.entity.User;
import com.aaa.book_mall.util.JDBCUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 客户表Controller
 * @ClassName: UserController
 * @Author: fengyun
 * @Date: 2021/2/21 10:56
 * @Version: 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserDao userDaoimpl;

    @RequestMapping("/login")
    public Map login(String username, String password, HttpServletRequest request){
        //System.out.println("dsdsdsdsdsdsdsdsdsds");
        System.out.println(username+""+password);
        User userByUP = userDaoimpl.getUserByUP(username, password);
        System.out.println(userByUP);
        HashMap<String, Object> map = new HashMap<>();
        if(userByUP==null){
            map.put("code",300);
            map.put("msg","该用户不存在");
        }else {
            request.getSession().setAttribute("user",userByUP);
            map.put("code",200);
        }
        return map;
    }

    @RequestMapping("/register")
    public Map userRegister(User user,HttpServletRequest request){
        System.out.println("register");
        System.out.println(user);
//        判断是否有重名
        int userer = userDaoimpl.getUserByUsername(user.getUsername());
        HashMap<String, Object> map = new HashMap<>();
        if(userer==1){
            map.put("code",300);
            map.put("msg","用户名已存在，请重新输入用户名");
            return map;
        }
//        判断验证码是否正确
//        String authcode = (String)request.getSession().getAttribute("authcode");
//        authcode.equals(user.getAuthcodeR())
        if(1==1){
            int i = userDaoimpl.insertUser(user);
            if(i>0){
                map.put("code",200);
                map.put("msg","注册成功");
            }else {
                map.put("code",300);
                map.put("msg","注册失败，请重新填写信息");
            }
            return map;
        }else {
            map.put("code",300);
            map.put("msg","验证码错误，请重新填写");
            return map;
        }
    }

    /**
     * 退出登录
     * @param request
     * @param response
     */
    @RequestMapping("/exit")
    public void userExit(HttpServletRequest request, HttpServletResponse response){
        request.getSession().invalidate();
        try {
            response.sendRedirect("/page/zhuye.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
